import os.path

import pytest
from typing import Generator
from httpx import AsyncClient

import llmapi
from llmapi.api import create_app
from llmapi.context import LLMAPIContext
from llmapi.config import LLMAPIConfig
from fastapi import FastAPI
from fastapi.testclient import TestClient
from llmapi.models import FakeModel
_model_loaded : bool = False


def pytest_configure():
    ctx = LLMAPIContext()
    config = LLMAPIConfig.parse_file(llmapi.CONFIG_YAML)
    ctx = LLMAPIContext(config=config)
    app = create_app(ctx)
    pytest.app = app


@pytest.fixture(scope="module")
def load_model():
    global _model_loaded
    if not _model_loaded:
        app : FastAPI = pytest.app
        ctx :LLMAPIContext = app.state.ctx
        ctx.models = ctx.config.load_models()
        _model_loaded = True

@pytest.fixture(scope="module")
def load_fake_model():
    app : FastAPI = pytest.app
    ctx :LLMAPIContext = app.state.ctx
    ctx.models["fake"] = FakeModel()

@pytest.fixture(scope="module")
async def async_client() -> Generator:

    async with AsyncClient(app=pytest.app,base_url="http://testserver") as client:

        yield client

@pytest.fixture
def get_client():
    client = TestClient(pytest.app)
    yield client